'use strict';

const Service = require('egg').Service;

class PermissionService extends Service {
  // 查询
  async find(page = 1, pageSize = 10) {
    const { ctx } = this;
    const offset = parseInt((page - 1) * pageSize);
    const list = await ctx.model.Permission.findAndCountAll({
      orders: [
        [ 'id', 'desc' ],
      ],
      limit: parseInt(pageSize),
      offset,
    });
    return {
      list,
    };
  }

  // 无分页查询
  async list() {
    const { ctx } = this;
    const list = await ctx.model.Permission.findAll();
    return {
      list,
    };
  }

  // 新增
  async create(body) {
    const { ctx } = this;
    const result = await ctx.model.Permission.create(body);
    return result ? 'success' : 'fail';
  }

  // 更新
  async update({
    id,
    name,
    describe,
    status,
    action_data,
    spt_da_types,
    optional_fields,
    parents,
    type,
    deleted,
    actions,
    action_entity_set,
  }) {
    const { ctx } = this;
    const result = await ctx.model.Permission.update({
      id,
      name,
      describe,
      status,
      action_data,
      spt_da_types,
      optional_fields,
      parents,
      type,
      deleted,
      actions,
      action_entity_set,
    }, {
      where: {
        id,
      },
    });
    return result ? 'success' : 'fail';
  }

  // 删除
  async delete(id) {
    const { ctx } = this;
    const result = await ctx.model.Permission.destroy({
      where: {
        id,
      },
    });
    return result ? 'success' : 'fail';
  }
}

module.exports = PermissionService;
